<!--
* description: 案例新增
* author: wangjuan
* createdDate: 2021-3-4
-->

<template>
  <section class="editStoreReturnRegistration">
    <el-dialog
      v-dialogDrag
      :visible.sync="curPopupsVisible"
      :title="textMap[popupsState]"
      :append-to-body="true"
      width="70%"
      :close-on-click-modal="false"
      @close="closeEdit"
    >
      <dialogHeader
        slot="title"
        :title="textMap[popupsState]"
        :style-type="$store.state.app.dialogType"
      />
      <div class="btns-container">
        <el-button
          v-for="comp in dynamictableButtons"
          :key="comp.compKey"
          :type="comp.type"
          :icon="comp.icon"
          @click="comp.clickEvent"
        >{{ comp.text }}</el-button>
      </div>
      <div class="filter-container filter-title">基本信息</div>
      <div class="filter-container filter-params">
        <el-row id="elrow" ref="vailComponentList1" :gutter="24">
          <component
            :is="comp.component"
            v-for="comp in tableComponents1.filter((o) => o.isMust === true)"
            :ref="comp.isRequire ? comp.isRequire + comp.compKey : comp.compKey"
            :key="comp.compKey"
            :validrule="comp.validrule"
            :code-field="comp.codeField"
            :text-field="comp.textField"
            :popups-key="comp.compKey"
            :parent-fileds="comp.parentFileds || ''"
            :code="formField[comp.codeField]"
            :disabled="comp.disabled"
            :is-require="comp.isRequire"
            :span="comp.span || 6"
            :label-name="comp.labelName"
            :lookuptype="comp.lookuptype"
            :options="comp.options"
            :o-fields="comp.oFields"
            @changeCode="getComponentCode"
          />
        </el-row>
      </div>
      <div class="filter-container filter-title">车辆信息</div>
      <div class="filter-container filter-params">
        <el-row id="elrow" ref="vailComponentList2" :gutter="24">
          <component
            :is="comp.component"
            v-for="comp in tableComponents2.filter((o) => o.isMust === true)"
            :ref="comp.isRequire ? comp.isRequire + comp.compKey : comp.compKey"
            :key="comp.compKey"
            :validrule="comp.validrule"
            :code-field="comp.codeField"
            :text-field="comp.textField"
            :popups-key="comp.compKey"
            :parent-fileds="comp.parentFileds || ''"
            :code="formField[comp.codeField]"
            :disabled="comp.disabled"
            :is-require="comp.isRequire"
            :span="comp.span || 6"
            :label-name="comp.labelName"
            :lookuptype="comp.lookuptype"
            :options="comp.options"
            :o-fields="comp.oFields"
            @changeCode="getComponentCode"
          />
        </el-row>
      </div>
      <div class="filter-container filter-title">车辆信息</div>
      <div class="filter-container filter-params">
        <el-row id="elrow" ref="vailComponentList3" :gutter="24">
          <component
            :is="comp.component"
            v-for="comp in tableComponents3.filter((o) => o.isMust === true)"
            :ref="comp.isRequire ? comp.isRequire + comp.compKey : comp.compKey"
            :key="comp.compKey"
            :validrule="comp.validrule"
            :code-field="comp.codeField"
            :text-field="comp.textField"
            :popups-key="comp.compKey"
            :parent-fileds="comp.parentFileds || ''"
            :code="formField[comp.codeField]"
            :disabled="comp.disabled"
            :is-require="comp.isRequire"
            :span="comp.span || 6"
            :label-name="comp.labelName"
            :lookuptype="comp.lookuptype"
            :options="comp.options"
            :o-fields="comp.oFields"
            @changeCode="getComponentCode"
          />
        </el-row>
      </div>
      <div class="eltabs">
        <el-tabs v-model="activeName" @tab-click="handleClick">
          <el-tab-pane label="附件" name="first">
            <one-table-template
              ref="multipleTable"
              :key="oneTableKey"
              :dynamic-buttons="tableButtons"
              :dynamic-api-config="apiConfig"
              :dynamic-table-cols="tableCols"
              :dynamic-form-fields="formField"
              :dynamic-is-show-more-btn="true"
              :dynamic-is-show-select="true"
              :dynamic-is-init-table="true"
              :dynamic-table-defult-height="300"
              :callback-obj="callbackObj"
            />
          </el-tab-pane>

          <el-tab-pane label="审核历史" name="second">
            <mix-table
              ref="tableList"
              :is-dialog="true"
              :is-more="true"
              :is-paging="true"
              :dynamic-table-cols="dynamictableCols"
              :table-height="300"
            />
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-dialog>
  </section>
</template>
<script>
import { oneTableWithViewTemplateMixins } from '@/components/mixins/oneTableWithViewTemplateMixins'
import { formMixins } from '@/components/mixins/formMixins'
import OneTableTemplate from '@/components/templates/oneTable'
import mixTable from '@/components/basicComponent/mixTable'
import { orgApis } from '@/api/caseManagementQuery'

export default {
  components: {
    OneTableTemplate,
    mixTable,
    dialogHeader: () => import('@/components/dialogHeader')
  },

  // 组件混入对象
  mixins: [oneTableWithViewTemplateMixins, formMixins],

  props: {
    popupsVisible: { type: Boolean, default: false },
    // 从网格传入的编辑行数据(json)
    dynamicEditRowData: { type: Object, default: function() { return {} } }
  },

  data() {
    return {
      tableList: [],
      activeName: 'first',
      // 动态组件-按钮
      dynamictableButtons: [
        {
          compKey: 'btnKey1',
          type: 'primary',
          size: 'small',
          icon: 'iconfont  icon-preservation',
          clickEvent: () => this.submit(),
          text: '提交',
          position: 'right'
        }
      ],

      tableButtons: [
        {
          compKey: 'btnKey1',
          type: 'primary',
          size: 'small',
          clickEvent: () => this.handFileListChange(),
          text: '新增',
          position: 'upload'
        },
        {
          compKey: 'btnKey2',
          size: 'small',
          clickEvent: () => this.del(),
          text: '删除',
          position: 'right'
        }
      ],

      tableComponents: [],
      tableComponents1: [
        {
          compKey: 'compKey0',
          labelName: '案例编号：',
          codeField: 'reportCode',
          component: () => import('@/components/org/commonInput'),
          type: 'inputText',
          isMust: true,
          disabled: true,
          span: 6
        },
        {
          compKey: 'compKey1',
          labelName: '提报日期：',
          codeField: 'submitDate',
          component: () => import('@/components/org/datePicker/datePicker'),
          type: 'datePicker',
          isMust: true,
          span: 6
        },
        {
          compKey: 'compKey2',
          labelName: '门店编码：',
          codeField: 'dlrCode',
          isMul: false,
          component: () => import('@/components/org/commonInput'),
          type: 'inputText',
          isMust: true,
          disabled: true,
          span: 6
        },
        {
          compKey: 'compKey3',
          labelName: '门店名称：',
          codeField: 'dlrFullName',
          isMul: false,
          component: () => import('@/components/org/commonInput'),
          type: 'inputText',
          isMust: true,
          disabled: true,
          span: 6
        },
        {
          compKey: 'compKey4',
          labelName: '维修工单：',
          codeField: 'repairOrderCode',
          isMul: false,
          component: () => import('@/components/org/commonInput'),
          type: 'inputText',
          isMust: true,
          disabled: false,
          span: 6
        },
        {
          compKey: 'compKey5',
          labelName: '重要程度：',
          codeField: 'reportLevelCode',
          isMul: false,
          component: () => import('@/components/org/LookupValue'),
          oFields: 'reportLevelCode,returnStatusName',
          options: [
            { reportLevelCode: '1', returnStatusName: '低' },
            { reportLevelCode: '2', returnStatusName: '中' },
            { reportLevelCode: '3', returnStatusName: '高' }
          ],
          type: 'dropdownList',
          isMust: true,
          isRequire: true,
          span: 6
        },
        {
          compKey: 'compKey6',
          labelName: '案例状态：',
          codeField: 'status',
          isMul: false,
          component: () => import('@/components/org/LookupValue'),
          oFields: 'status,statusName',
          options: [
            { status: '1', statusName: '保存' },
            { status: '2', statusName: '提交' },
            { status: '3', statusName: '驳回' },
            { status: '4', statusName: '审核通过' }
          ],
          type: 'dropdownList',
          isMust: true,
          span: 6
        }
      ],
      tableComponents2: [
        {
          compKey: 'compKey7',
          labelName: 'VIN码：',
          codeField: 'vin',
          component: () => import('@/components/se/VIN'),
          type: 'inputText',
          isMust: true,
          isRequire: true,
          span: 6
        },
        {
          compKey: 'compKey9',
          labelName: '车系：',
          codeField: 'carSeriesCn',
          component: () => import('@/components/org/commonInput'),
          type: 'inputText',
          isMust: true,
          disabled: true,
          span: 6
        },
        {
          compKey: 'compKey8',
          labelName: '车型名称：',
          codeField: 'carConfigCn',
          component: () => import('@/components/org/commonInput'),
          type: 'inputText',
          isMust: true,
          disabled: true,
          span: 6
        },
        {
          compKey: 'compKey10',
          labelName: '销售日期：',
          codeField: 'saleDate',
          component: () => import('@/components/org/commonInput'),
          type: 'inputText',
          isMust: true,
          disabled: true,
          span: 6
        },
        {
          compKey: 'compKey11',
          labelName: '生产日期：',
          codeField: 'produceDate',
          component: () => import('@/components/org/commonInput'),
          type: 'inputText',
          isMust: true,
          disabled: true,
          span: 6
        }
      ],
      tableComponents3: [
        {
          compKey: 'compKey12',
          labelName: '故障编码：',
          codeField: 'faultCode',
          component: () => import('@/components/org/commonInput'),
          type: 'inputText',
          isMust: true,
          isRequire: true,
          span: 6
        },
        {
          compKey: 'compKey13',
          labelName: '故障部位：',
          codeField: 'faultPartCode',
          component: () => import('@/components/org/LookupValue'),
          oFields: 'faultPartCode,faultPartName',
          options: [
            { faultPartCode: '1', faultPartName: '车身' },
            { faultPartCode: '2', faultPartName: '驾驶室' },
            { faultPartCode: '3', faultPartName: '底盘' }
          ],
          type: 'dropdownList',
          isMust: true,
          isRequire: true,
          span: 6
        },
        {
          compKey: 'compKey14',
          labelName: '故障日期：',
          codeField: 'faultDate',
          component: () => import('@/components/org/datePicker/datePicker'),
          type: 'datePicker',
          isMust: true,
          isRequire: true,
          span: 6
        },
        {
          compKey: 'compKey15',
          labelName: '主故障件号：',
          codeField: 'mainPartCode',
          component: () => import('@/components/org/commonInput'),
          type: 'inputText',
          isMust: true,
          isRequire: true,
          span: 6
        },
        {
          compKey: 'compKey16',
          labelName: '主故障件名称：',
          codeField: 'mainPartName',
          component: () => import('@/components/org/commonInput'),
          type: 'inputText',
          isMust: true,
          isRequire: true,
          span: 6
        },
        {
          compKey: 'compKey17',
          labelName: '主题：',
          codeField: 'topic',
          component: () => import('@/components/org/commonInput'),
          type: 'inputText',
          isMust: true,
          span: 24
        },
        {
          compKey: 'compKey18',
          labelName: '故障描述：',
          codeField: 'faultDesc',
          component: () => import('@/components/org/commonInput/textareaInput'),
          type: 'inputText',
          isMust: true,
          span: 24
        },
        {
          compKey: 'compKey19',
          labelName: '维修方案：',
          codeField: 'repairMethod',
          component: () => import('@/components/org/commonInput/textareaInput'),
          type: 'inputText',
          isMust: true,
          span: 24
        }
      ],

      tableCols:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          .length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          : [
            {
              prop: 'releaseId',
              label: '主键ID',
              hidden: true,
              alwaysHidden: true
            },
            {
              prop: 'updateControlId',
              label: '并发控制ID',
              hidden: true,
              alwaysHidden: true
            },
            {
              prop: 'fileName',
              label: '附件名称',
              isComponent: true,
              comps: [
                {
                  compKey: 'propKey1',
                  codeField: 'fileName',
                  component: () => import('@/components/org/linkButton'),
                  clickEvent: (index) => this.downFile(index)
                }
              ]
            },
            {
              prop: 'fileSite',
              label: '附件地址'
            }
          ],

      dynamictableCols: [
        {
          codeField: 'releaseId',
          label: '主键ID',
          hidden: true,
          alwaysHidden: true
        },
        {
          codeField: 'updateControlId',
          label: '并发控制ID',
          hidden: true,
          alwaysHidden: true
        },
        {
          codeField: 'checkEmpid',
          label: '审核人'
        },
        {
          codeField: 'checkDate',
          label: '审核时间'
        }
      ],

      // 标题
      textMap: {
        add: '案例新增'
      },

      formField: {
        reportCode: '',
        submitDate: '',
        dlrCode: '',
        dlrFullName: '',
        repairOrderCode: '',
        reportLevelCode: '',
        status: '',

        vin: '',
        carConfigCn: '',
        carSeriesCn: '',
        saleDate: '',
        produceDate: '',

        faultCode: '',
        faultPartCode: '',
        faultDate: '',
        mainPartCode: '',
        mainPartName: '',
        topic: '',
        faultDesc: '',
        repairMethod: ''
      },

      callbackObj: {
        onCheckSelectChange: (selection) => {
          this.selectData = selection
          this.handleSelectionChange(selection)
        }
      }
    }
  },

  watch: {
    'formField.vin': {
      deep: true,
      handler: function(val) {
        if (val) {
          this.queryCarInfo()
        }
      }
    }
  },

  created() {
    this.tableComponents = [...this.tableComponents1, ...this.tableComponents2, ...this.tableComponents3]
  },

  methods: {
    queryCarInfo() {
      const queryObj = {
        // 保存mutation
        type: 'mutation',
        // api配置
        apiConfig: orgApis.findCarDetailByVin,
        // 条件/实体参数（变量），根据typeParam中的定义配置
        variables: {
          vin: this.formField.vin
        }
      }
      // 转换了中台请求格式数据
      var paramD = this.$getParams(queryObj)
      this.$requestAPI(paramD).then(response => {
        if (response.result === '1') {
          this.formField.carConfigCn = response.rows[0].carConfigCn
          this.formField.carSeriesCn = response.rows[0].carSeriesCn
          this.formField.saleDate = response.rows[0].saleDate
          this.formField.produceDate = response.rows[0].produceDate
        }
      })
    },

    // 提交
    submit() {
      this.$utils.validataMoth(this, 'validpopup')
      if (this.valid) {
        const dataTable = { ...this.formField, fileLists: this.$refs.multipleTable.list }

        const queryObj = {
          // 保存mutation
          type: 'mutation',
          // api配置
          apiConfig: orgApis.addTechnicalSupport,
          // 条件/实体参数（变量），根据typeParam中的定义配置
          variables: {
            dataInfo: dataTable
          }
        }
        // 转换了中台请求格式数据
        var paramD = this.$getParams(queryObj)
        // 调用中台API方法（可复用）
        this.$requestAPI(paramD).then(response => {
          if (response.result === '1') {
            this.$message({
              message: response.msg,
              type: 'success',
              duration: 1000
            })
            this.closeEdit()
            this.$parent.queryTable(1)
          } else {
            this.$message({
              message: response.msg,
              type: 'warn',
              duration: 1000
            })
          }
        })
      }
    },
    handFileListChange(file, fileList) {
      this.handleChange(file)
    },
    handleChange(param) {
      const that = this
      const url = '/mp/file/commonUpload/upload.do'
      that
        .$requestUpload(url, param)
        .then((response) => {
          if (response.result === '1') {
            //  路径
            const fileSite = response.path[0][0].split('|')[1]
            // 文件名
            const fileName = response.path[0][0].split('|')[0]
            const dataParmas = { fileName, fileSite }
            // that.addFilePath(dataParmas);
            that.dataForm = dataParmas
            that.$refs['multipleTable'].list.push(that.dataForm)
          }
        })
    },

    del() {
      for (const i of this.selectData) {
        this.$refs['multipleTable'].list = this.$refs['multipleTable'].list.filter((item) => item !== i)
      }
    },

    // 当选择项发生变化时会触发该事件
    handleSelectionChange(selection) {
      const btns = this.dynamictableButtons.filter((o) => o.disabled !== undefined)
      if (btns.length > 0) {
        const isCheck = selection && selection.length > 0
        btns.forEach((item) => {
          item.disabled = !isCheck
        })
      }
    },

    handleClick(tab, event) {
      // console.log(tab, event)
    },

    closeEdit() {
      this.$emit('update:popupsVisible', false)
      this.oneTableKey = this.$utils.generateId()
    }
  }
}
</script>

<style lang="scss" scoped>
.btns-container {
  width: 100%;
  height: 30px;
  padding: 0 20px;
  background-color: #fff;
  .el-button {
    float: right;
    margin-left: 10px;
  }
}
  .filter-title{
    font-size: 18px;
    font-weight: bolder;
  }
  .filter-container.filter-title::before{
    border-left: 4px solid #0075FF;
    padding-right: 10px;
    height: 20px;
    left: 0px;
    top: 4px;
  }
  .eltabs {
  background-color: #fff;
}
</style>

